<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row>
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" class="btn" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表表格 -->
      <el-table :data="usersList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="item">
            <!-- {{item.row}}  插槽作用域  获取每行数据-->
            <el-switch v-model="item.row.mg_state" @change="userStatusChange(item.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="item">
            <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="editUser(item.row.id)"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="delUser(item.row.id)"></el-button>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top">
              <el-button size="mini" type="warning" icon="el-icon-setting" circle></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户弹框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogVisibleClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" >
          <el-input v-model="addForm.password" ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%" @close="editDialogVisibleClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="70px">
        <el-form-item label="用户名" >
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱规则
    let checkMail = (rule,val,cb) => {
      var Reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if(Reg.test(val)) {
        return cb()
      }
      cb(new Error('你输入的邮箱格式不正确'))
    }
    let checkMobile = (rule,val,cb) => {
      var Reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if(Reg.test(val)) {
        return cb()
      }
      cb(new Error('你输入的手机号码格式不正确'))
    }
    return {
      // 获取用户列表的参数
      queryInfo: {
        query: '', // 查询参数
        pagenum: 1, // 当前页数
        pagesize: 2 // 每页显示多少条
      },
      total: 0,
      usersList: [],
      // 添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm:{
        // 命名与接口文档添加用户参数一致
        username:'test',
        password:'123456',
        email:'123@123.com',
        mobile:'13888888888'
      },
      // 添加用户表单的验证规则
      addFormRules:{
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 7, message: '用户名长度在 2 到 7 个字符', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 15, message: '密码长度在 5 到 15 个字符', trigger: 'blur' }
        ],
        email:[
           { required: true, message: '请输入邮箱', trigger: 'blur' },
           { validator:checkMail, trigger:'blur' }
        ],
        mobile:[
           { required: true, message: '请输入手机号', trigger: 'blur' },
           { validator:checkMobile, trigger:'blur' }
        ]
      },
      // 修改用户对话框的显示与隐藏
      editDialogVisible:false,
      // 编辑用户数据
      editForm: {},
      // 编辑用户表单规则
      editFormRules:{
        email:[
           { required: true, message: '请输入邮箱', trigger: 'blur' },
           { validator:checkMail, trigger:'blur' }
        ],
        mobile:[
           { required: true, message: '请输入手机号', trigger: 'blur' },
           { validator:checkMobile, trigger:'blur' }
        ]
      }
    }
  },

  methods: {
    // 获取用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      // console.log(res)
      if (res.meta.status != 200) return this.$message.error('服务器错误')
      this.total = res.data.total
      this.usersList = res.data.users
      // console.log(this.total )
      // console.log(this.users )
    },
    // 下拉框 条/页
    handleSizeChange(val) {
      // console.log(val)
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 改变当前页
    handleCurrentChange(val) {
      // console.log(val)
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 改变状态
    async userStatusChange(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      // console.log(res)
      if (res.meta.status != 200) {
        userInfo.mg_state = !userInfo.mg_state // 用户更新失败  把状态恢复到之前
        return this.$message.error('用户状态更新失败')
      }
      this.$message.success('用户状态更新成功')
    },
    // 监听添加用户对话框关闭事件
    addDialogVisibleClose() {
      this.$refs.addForm.resetFields()
    },
    // 添加用户表单预校验
    addUser() {
      this.$refs.addForm.validate(async flag => {
        if(flag) {
          var { data:res } = await this.$http.post('/users',this.addForm)
          console.log(res)
          // 判断是否创建成功并提示用户
          if(res.meta.status == 201) {
            this.$message.success(res.meta.msg)
          } else {
            this.$message.error(res.meta.msg)
          }
          this.addDialogVisible = false;
          this.getUserList()
        }
        
      })
    },
    // 编辑用户 点击编辑按钮渲染数据到表单中
    async editUser(id) {
      this.editDialogVisible = true
      // console.log(id)
      var { data:res } = await this.$http.get('users/' + id)
      // console.log(res)
      this.editForm = res.data
      console.log(this.editForm)
    },
    // 重置表单和校验规则
    editDialogVisibleClose() {
      this.$refs.editForm.resetFields()
    },
    // 点击提交修改
    submitEdit() {
      //提交之前进行预校验
      this.$refs.editForm.validate(async flag => {
        // console.log(flag)
        // console.log(id)
        if(flag) {
          var { data:res } = await this.$http.put('users/'+editForm.id,{
            email:this.editForm.email,
            mobile:this.editForm.mobile})
          // console.log(res)
          if(res.meta.status == 200) {
            this.$message.success('修改成功')
          } else {
            this.$message.error('修改失败')
          }
          this.editDialogVisible = false;
          this.getUserList()
        }
      })
      
    },
    // 删除用户
    async delUser(id) {
      var result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)//捕获点击取消出错
        // console.log(result)
        if(result == 'confirm') {
          var {data:res} = await this.$http.delete('users/'+id)
          console.log(res)
          if(res.meta.status == 200) {
            this.$message.success('删除成功')
          } else {
            this.$message.error('服务器错误')
          }
        } else {
          this.$message.info('用户取消删除')
        }
    }
  },

  created() {
    this.getUserList()
  }
}
</script>

<style lang='css' scoped>
.btn {
  margin-left: 20px;
}
</style>

